<script>
import Select from "./components/Select.vue";
import Radio from "./components/Radio.vue";
import CheckBox from "./components/CheckBox.vue";
import Cascader from "./components/Cascader.vue";
import Upload from "./components/Upload.vue";
import Input from "./components/Input.vue";
import Switchs from "./components/Switch.vue";
import DatePickerRange from "./components/DatePickerRange.vue";
import DatePicker from "./components/DatePicker.vue";

import axios from "axios";

export default {
  name: "itemAPI",
  components: {
    Select,
    Radio,
    CheckBox,
    Cascader,
    Upload,
    Input,
    Switchs,
    DatePickerRange,
    DatePicker,
  },
  props: {
    value: [Number, String, Array, Object, Boolean, undefined, null],
    config: Object,
  },
  data() {
    return {
      form: {},
      type: [
        { name: "select", component: Select },
        { name: "radio", component: Radio },
        { name: "checkbox", component: CheckBox },
        { name: "cascader", component: Cascader },
        { name: "upload", component: Upload },
        { name: "input", component: Input },
        { name: "switch", component: Switchs },
        { name: "datetimerange", component: DatePickerRange },
        { name: "datetime", component: DatePicker },
      ],
      configSelf: {},
      commonNode: null,
    };
  },
  computed: {
    valueSelf() {
      return this.value;
    },
  },
  methods: {
    change(value) {
      console.log(value);
      // this.$emit("itemInput");
      this.$emit("input", value);
    },
  },
  async mounted() {
    const comObj = this.type.find((e) => e.name === this.config.type);
    this.commonNode = comObj.component;
    this.configSelf = { ...this.config };
    // 有请求数据就请求数据没有就默认去options
    if (this.config?.api) {
      const res = await axios.get(this.config?.api);
      const arr = this.config?.apiLabel
        ? res?.data[this.config?.apiLabel]
        : res?.data || [];
      // 数组重组
      const arrNew = this.config?.optionsRebuildFuc
        ? this.config?.optionsRebuildFuc(arr)
        : arr;
      this.$set(this.configSelf, "options", arrNew);
    }
  },
  render() {
    const commonNode = this.commonNode;
    return (
      <commonNode
        value={this.valueSelf}
        change={this.change}
        config={this.configSelf}
      />
    );
  },
};
</script>
